// 中断相关操作安全包装

use thiserror::Error;
use super::api;
use super::capability::ThreadSafeCapability;

// 定义中断错误类型
#[derive(Error, Debug)]
pub enum InterruptError {
    #[error("Interrupt handler setup failed")]
    HandlerSetupFailed,
    
    #[error("Interrupt trigger failed")]
    TriggerFailed,
    
    #[error("Invalid interrupt capability")]
    InvalidCapability,
    
    #[error("Invalid IRQ number")]
    InvalidIrq,
    
    #[error("Invalid handler address")]
    InvalidHandler,
}

// 定义中断结果类型
pub type InterruptResult<T> = Result<T, InterruptError>;

// 中断管理器
pub struct InterruptManager {
    capability: ThreadSafeCapability,
}

impl InterruptManager {
    // 创建新的中断管理器
    pub fn new(capability: ThreadSafeCapability) -> InterruptResult<Self> {
        // 验证能力是否为中断类型
        if let Ok(cap) = capability.lock() {
            if cap.resource_type() != super::super::core::types::ResourceType::Interrupt {
                return Err(InterruptError::InvalidCapability);
            }
        } else {
            return Err(InterruptError::InvalidCapability);
        }
        
        Ok(InterruptManager {
            capability,
        })
    }
    
    // 设置中断处理程序
    pub fn set_handler(&self, irq: u32, handler: u64) -> InterruptResult<bool> {
        // 验证IRQ号是否有效（这里简单验证）
        if irq >= 256 {
            return Err(InterruptError::InvalidIrq);
        }
        
        // 验证处理程序地址是否有效
        if handler == 0 {
            return Err(InterruptError::InvalidHandler);
        }
        
        // 获取能力ID
        let cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(InterruptError::HandlerSetupFailed);
        };
        
        // 调用FFI设置中断处理程序
        let result = unsafe {
            api::exokernel_set_interrupt_handler(cap_id, irq, handler)
        };
        
        if result {
            Ok(true)
        } else {
            Err(InterruptError::HandlerSetupFailed)
        }
    }
    
    // 触发中断
    pub fn trigger(&self, irq: u32) -> InterruptResult<bool> {
        // 验证IRQ号是否有效
        if irq >= 256 {
            return Err(InterruptError::InvalidIrq);
        }
        
        // 获取能力ID
        let cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(InterruptError::TriggerFailed);
        };
        
        // 调用FFI触发中断
        let result = unsafe {
            api::exokernel_trigger_interrupt(cap_id, irq)
        };
        
        if result {
            Ok(true)
        } else {
            Err(InterruptError::TriggerFailed)
        }
    }
}

// 驱动中断管理器
pub struct DriverInterruptManager {
    capability: ThreadSafeCapability,
}

impl DriverInterruptManager {
    // 创建新的驱动中断管理器
    pub fn new(capability: ThreadSafeCapability) -> InterruptResult<Self> {
        // 验证能力是否有效
        if let Err(_) = capability.lock() {
            return Err(InterruptError::InvalidCapability);
        }
        
        Ok(DriverInterruptManager {
            capability,
        })
    }
    
    // 注册驱动中断处理程序
    pub fn register_handler(&self, irq: u32, handler: u64) -> InterruptResult<bool> {
        // 验证IRQ号是否有效
        if irq >= 256 {
            return Err(InterruptError::InvalidIrq);
        }
        
        // 验证处理程序地址是否有效
        if handler == 0 {
            return Err(InterruptError::InvalidHandler);
        }
        
        // 获取能力ID
        let cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(InterruptError::HandlerSetupFailed);
        };
        
        // 调用FFI注册驱动中断处理程序
        let result = unsafe {
            api::exokernel_driver_register_irq_handler(cap_id, irq, handler)
        };
        
        if result {
            Ok(true)
        } else {
            Err(InterruptError::HandlerSetupFailed)
        }
    }
    
    // 注销驱动中断处理程序
    pub fn unregister_handler(&self, irq: u32) -> InterruptResult<bool> {
        // 验证IRQ号是否有效
        if irq >= 256 {
            return Err(InterruptError::InvalidIrq);
        }
        
        // 获取能力ID
        let cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(InterruptError::HandlerSetupFailed);
        };
        
        // 调用FFI注销驱动中断处理程序
        let result = unsafe {
            api::exokernel_driver_unregister_irq_handler(cap_id, irq)
        };
        
        if result {
            Ok(true)
        } else {
            Err(InterruptError::HandlerSetupFailed)
        }
    }
    
    // 发送中断结束信号
    pub fn send_eoi(&self, irq: u32) -> InterruptResult<()> {
        // 验证IRQ号是否有效
        if irq >= 256 {
            return Err(InterruptError::InvalidIrq);
        }
        
        // 获取能力ID
        let cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(InterruptError::TriggerFailed);
        };
        
        // 调用FFI发送EOI
        unsafe {
            api::exokernel_driver_send_eoi(cap_id, irq);
        }
        
        Ok(())
    }
}